package com.base.cn.platform.os.service.integralgood;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;

import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.dao.integralgood.IntegralExchangeRecordDao;

import com.base.cn.platform.os.entity.integralgood.IntegralExchangeRecord;
import com.base.cn.platform.os.entity.integralgood.IntegralExchangeRecordExpand;
import com.base.cn.platform.os.entity.integralgood.IntegralGood;

import com.base.cn.platform.os.entity.op.affiche.OpAffiche;
import com.base.cn.platform.os.entity.user.user.CusUser;

import com.base.cn.platform.os.service.manage.op.affiche.OpReceiveAfficheService;
import com.base.cn.platform.os.service.op.affiche.OpAfficheBiz;
import com.base.cn.platform.os.service.op.affiche.OpReceiveAfficheBiz;
import com.base.cn.platform.os.service.user.user.CusUserBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 兑换商品记录
 * @Author: Hello豆包
 * @Date: 2019/10/18 14:498
 */
@Service
public class IntegralExchangeRecordBiz extends BaseBiz<IntegralExchangeRecord, IntegralExchangeRecordDao> {

    @Autowired
   private   IntegralGoodBiz integralGoodBiz;
   @Autowired
   private CusUserBiz cusUserBiz;
   @Autowired
   private OpReceiveAfficheService opReceiveAfficheService;


    /**
     * 发货
     * @param parameter
     */
    @Transactional(rollbackFor = IllegalArgumentException.class)
    public void toSendExpress(Map parameter){

        IntegralExchangeRecord integralExchangeRecord = new IntegralExchangeRecord();
        integralExchangeRecord.setId(new BigDecimal(parameter.get("id").toString()));
        integralExchangeRecord.setNotDeliver(1);
        integralExchangeRecord.setCourierNumber(parameter.get("courierNumber").toString());
        integralExchangeRecord.setTheSenderId(new BigDecimal(parameter.get("loginUserId").toString()));
        this.updateById(integralExchangeRecord,null);
        HashMap<String, Object> entity = new HashMap<>();
        //消息内容
        if(StringUtils.isEmpty(parameter.get("content"))){
            entity.put("context","您兑换的"+parameter.get("name")+"已发货，快递单号为"+parameter.get("courierNumber"));
        }else{
            entity.put("context",parameter.get("content"));
        }
        entity.put("msgType", 2);
        entity.put("status", 1);
        entity.put("userIds", new BigDecimal(parameter.get("userId").toString()));
        opReceiveAfficheService.saveReceiveAffiche(entity);
        IntegralGood shopId = integralGoodBiz.findById(new BigDecimal(parameter.get("shopId").toString()), false);
        IntegralGood integralGood = new IntegralGood();
        integralGood.setId(shopId.getId());
        integralGood.setNotDeliverNum( shopId.getNotDeliverNum()>0?shopId.getNotDeliverNum()-1:0);
        integralGoodBiz.updateById(integralGood,null);
    }
    /**
     * 分页数据
     * @param page
     * @param integralExchangeRecord
     * @return
     */
    public PageInfo<IntegralExchangeRecord>findListPage(Pagination page, IntegralExchangeRecordExpand integralExchangeRecord){

        String s = whereSql(integralExchangeRecord);
        PageInfo<IntegralExchangeRecord> pageInfo = this.findPage(s, page, null);
        setIntegralGood(pageInfo.getList(),integralExchangeRecord.isSetIntegralGood());
        setUser(pageInfo.getList(),integralExchangeRecord.isSetUser());
        return pageInfo;
    }


    /**
     * 设置商品
     * @param integralExchangeRecords
     * @param isSetIntegralGood
     */
    public  void setIntegralGood(List<IntegralExchangeRecord> integralExchangeRecords,boolean isSetIntegralGood){

        if(isSetIntegralGood&&ObjectUtils.isNotEmpty(integralExchangeRecords)){
            Set<String> shopId = new HashSet<>();
            integralExchangeRecords.stream().forEach(e->{
                if(  ObjectUtils.isNotEmpty(e.getIntegralShopId())){
                    shopId.add(e.getIntegralShopId().toString());
                }
            });
            String sellTypeList = shopId.stream().collect(Collectors.joining(","));
            ArrayList<String> objects = new ArrayList<>();
            objects.add("id");
            objects.add("name");
            objects.add("imageJson");
            if(StringUtils.isNotEmpty(sellTypeList)){
                List<IntegralGood> integralGoods = integralGoodBiz.find(" id in (" + sellTypeList + ")", null, objects);
                Map<BigDecimal, IntegralGood> shopDataListMap = integralGoods.stream().collect(Collectors.toMap(IntegralGood::getId, e -> e));
                for(IntegralExchangeRecord entity:integralExchangeRecords){
                    entity.setIntegralGood(shopDataListMap.get(entity.getIntegralShopId()));
                }
            }
        }
    }

    /**
     * 设置兑换人
     * @param integralExchangeRecords
     * @param isSetUser
     */
    public  void setUser(List<IntegralExchangeRecord> integralExchangeRecords,boolean isSetUser){

        if(isSetUser&&ObjectUtils.isNotEmpty(integralExchangeRecords)){
            Set<String> shopUser = new HashSet<>();
            integralExchangeRecords.stream().forEach(e->{
                if(  ObjectUtils.isNotEmpty(e.getUserId())){
                    shopUser.add(e.getUserId().toString());
                }
            });
            String sellList = shopUser.stream().collect(Collectors.joining(","));
            ArrayList<String> objects = new ArrayList<>();
            objects.add("id");
            objects.add("nickname");

            List<CusUser> cusUsers = cusUserBiz.find(" id in (" + sellList + ")", null, objects);
            Map<BigDecimal, CusUser> shopDataListMap = cusUsers.stream().collect(Collectors.toMap(CusUser::getId, e -> e));
            for(IntegralExchangeRecord entity:integralExchangeRecords){
                entity.setCusUser(shopDataListMap.get(entity.getUserId()));
            }
        }
    }


    private  String  whereSql(IntegralExchangeRecordExpand integralExchangeRecord){

        StringBuilder sql  = new StringBuilder(" 1 = 1");
            if(ObjectUtils.isNotEmpty(integralExchangeRecord)){
                if(DataUtil.idIsNotNull(integralExchangeRecord.getUserId())){
                    sql.append(" and userId = ").append(integralExchangeRecord.getUserId());
                }
                if(DataUtil.idIsNotNull(integralExchangeRecord.getShopId())){
                    sql.append(" and shopId = ").append(integralExchangeRecord.getShopId());
                }
                if(DataUtil.idIsNotNull(integralExchangeRecord.getIntegralShopId())){
                    sql.append(" and integralShopId = ").append(integralExchangeRecord.getIntegralShopId());
                }
            }
             sql.append(" order by  updateTime desc ");

        return  sql.toString();

    }
}
